package com.ls.utils;

import com.ls.entity.SysUser;
import com.ls.exception.SysException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 文件操作工具类
 * </p>
 *
 * @author TangQuanBin
 * @since 2019/10/16 9:23
 */
@Component
public class FileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    @Value("${upload.temp.dir}")
    private String UPLOAD_TEMP_DIR;


    //存储位置
    public static String baseTempPath ="";
    //springboot无法直接操作一个静态变量
    @Value("${upload.temp.dir}")
    public void setBasePathString(String basePathString) {
        baseTempPath = basePathString;
    }



    /**
     * 循环删除文件夹下的文件
     *
     * @param file 要删除的文件夹 File
     * @return true 删除成功
     */
    public static boolean deleteFile(File file) throws Exception {
        if (!file.exists()) {
            return false;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteFile(f);
            }
        }
        return file.delete();
    }
    public static String listGetTrim(List list, int index){
        if(list == null){
            return StringUtils.EMPTY;
        }
        if(index >= list.size()){
            return StringUtils.EMPTY;
        }
        if(null == list.get(index)){
            return StringUtils.EMPTY;
        }
        return StringUtils.trimToEmpty(list.get(index).toString());
    }

    public static File createTempFile(MultipartFile file){
        if (file.isEmpty()) {
            throw new SysException("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        String filePath = baseTempPath
                + File.separator
                + DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.format(System.currentTimeMillis())
                + File.separator;
        //名字添加前缀
        fileName = UUID.randomUUID().toString().replace("-", "") + "_" + fileName;
        File dest = new File(filePath, fileName);
        try {
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            LOGGER.info("{}上传成功", fileName);
        } catch (IOException e) {
            LOGGER.error("transferTo error", e);
            throw new SysException("上传文件失败");
        }
        return dest;
    }
}
